<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2019/7/5
 * Time: 12:07
 */

namespace iBrand\Shop\Backend\Service;


use iBrand\Component\Order\Repositories\OrderRepository;
use iBrand\Component\Purchase\Repositories\StockRecordRepository;
use iBrand\Shop\Core\Models\UserShop;
use iBrand\Shop\Core\Repositories\O2oGoodsRepository;
use Illuminate\Support\Facades\DB;

class DashboardService
{
    protected $orderRepository;
    protected $o2oGoodsRepository;
    protected $stockRecordRepository;

    public function __construct(OrderRepository $orderRepository,
                                O2oGoodsRepository $o2oGoodsRepository,
                                StockRecordRepository $stockRecordRepository)
    {
        $this->orderRepository = $orderRepository;
        $this->o2oGoodsRepository = $o2oGoodsRepository;
        $this->stockRecordRepository = $stockRecordRepository;
    }

    /**
     * 获取当天销售数据
     * @param $shop_id
     * @return array
     */
    public function getCurrentSaleData($shop_id)
    {
        $orders = $this->orderRepository->scopeQuery(function ($query) use ($shop_id) {
            return $query->where(DB::raw('date(created_at)'), DB::raw('curdate()'))
                ->where('channel', 'shop')
                ->where('channel_id', $shop_id)
                ->where('status', 2);
        })->all();

        $total_amount = $orders->sum('total') / 100;
        $count = $orders->count();
        $quantity = $orders->sum('count');

        $cost_price = 0;
        foreach ($orders as $order) {
            foreach ($order->items as $item) {
                $cost_price += $item->getFactoryPrice();
            }
        }
        $grossProfit = $total_amount - $cost_price;

        $userCount = UserShop::where(DB::raw('date(created_at)'), DB::raw('curdate()'))->where('shop_id', $shop_id)->count();

        return [
            'total_amount' => $total_amount,
            'count' => $count,
            'grossProfit' => $grossProfit,
            'userCount' => $userCount,
            'quantity' => $quantity
        ];

    }

    /**
     * 根据年份季节获取库存数据
     * @param $year
     * @param $season
     * @return array
     */
    public function getStockData($shop_id, $year, $season)
    {
        $goods = $this->o2oGoodsRepository->scopeQuery(function ($query) use ($shop_id) {
            return $query->where('shop_id', $shop_id);
        })->whereHas('goods', function ($query) use ($year, $season) {
            return $query = $query->where('season_id', $season)
                ->where('year', 'like', '%' . $year . '%');
        })->all();

        $purchaseAmount = 0;
        $store_nums = 0;
        if ($goods->count()) {
            $store_nums = $goods->sum('store_nums');
            foreach ($goods as $good) {
                $amount = $good->store_nums * $good->goods->factory_price;
                $purchaseAmount += $amount;
            }
        }

        return ['store_nums' => $store_nums, 'purchaseAmount' => $purchaseAmount];
    }

    /**
     * 获取最近4周平均月销量
     * @param $shop_id
     * @return int
     */
    public function getWeekSaleData($shop_id)
    {
        //SELECT * FROM ibrand_store_stock_record where created_at >=curdate() - INTERVAL 28 DAY and created_at < curdate()

        $records = $this->stockRecordRepository->scopeQuery(function ($query) use ($shop_id) {
            return $query->where('shop_id', $shop_id)
                ->where('type', 'STORE_SALES')
                ->where('created_at', '>=', DB::raw('curdate() - INTERVAL 28 DAY'))
                ->where('created_at', '<', DB::raw('curdate()'));
        })->all();

        $count = -$records->sum('change_count');
        return intval($count / 4);
    }

    public function getSeasonData()
    {
        $month = date('n');
        $year = date('Y');

        $season = [
            $year . '-1' => $year . '春',
            $year . '-2' => $year . '夏',
            $year . '-3' => $year . '秋',
            $year . '-4' => $year . '冬'
        ];

        if ($month >= 1 AND $month <= 3) {
            $currentSeason = 1;

        } elseif ($month > 3 AND $month <= 6) {
            $currentSeason = 2;
        } elseif ($month > 6 AND $month <= 9) {
            $currentSeason = 3;
        } else {
            $currentSeason = 4;
        }
        $currentKey = $year . '-' . $currentSeason;

        if ($currentSeason == 1) {
            array_splice($season, 0, 0, [$year - 1 . '-4' => $year - 1 . '冬']);
        }

        if ($currentSeason == 4) {
            array_splice($season, count($season), 0, [$year + 1 . '-1' => $year + 1 . '春']);
        }

        return ['currentKey' => $currentKey, 'seasons' => $season];

    }


}